package com.theBlind.orm.proxy;

import com.theBlind.orm.SqlSession;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: orm
 * @description:
 * @author: TheBlind
 * @create: 2021-04-23 17:15
 **/
public class MapperProxy implements InvocationHandler {

    /**
     * 需要代理对象
     */
    private SqlSession sqlSession;
    public MapperProxy(SqlSession sqlSession) {
        this.sqlSession = sqlSession;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        String statement = method.getDeclaringClass().getName()+"."+method.getName();

        //isAssignableFrom方法是判断是否为某个类的父类
        if(Collection.class.isAssignableFrom(method.getReturnType())) {
            //返回值是集合的话，那么是调用selectList
            return sqlSession.selectList(statement,argsHandle( method,args));
        }else {
            return sqlSession.selectOne(statement,argsHandle(method,args));
        }
    }

    Object argsHandle(Method method,Object[] args){
        if(null==args){
            return null;
        }
        Parameter[] parameters = method.getParameters();
        Map map=new HashMap();
        for (int i = 0; i < parameters.length; i++) {
            String name = parameters[i].getName();
            map.put(name,args[i]);
        }

        return map;
    }

}
